package cn.mikeal.cleandata;

import java.io.IOException;
import java.text.ParseException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import cn.mikeal.bean.WebLogBean;
import cn.mikeal.utils.WebLogParseUtils;

public class CleanData {

	static class CleanDataMapper extends Mapper<LongWritable, Text, Text, WebLogBean> {
		private Text mk = new Text();

		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, WebLogBean>.Context context)
				throws IOException, InterruptedException {
			String line = value.toString();
			WebLogBean bean = new WebLogBean();
			try {
				bean = WebLogParseUtils.parse(line);
			} catch (ParseException e) {
				bean = null;
				e.printStackTrace();
			}
			if (bean != null) {
				mk.set(bean.getTime_local());
				context.write(mk, bean);
			}
		}
	}

	static class CleanDataReducer extends Reducer<Text, WebLogBean, Text, NullWritable> {
		private Text rk = new Text();

		@Override
		protected void reduce(Text key, Iterable<WebLogBean> values,
				Reducer<Text, WebLogBean, Text, NullWritable>.Context context)
				throws IOException, InterruptedException {
			for (WebLogBean bean : values) {
				rk.set(bean.toString());
				context.write(rk, NullWritable.get());
			}
		}

	}

	public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
		System.setProperty("HADOOP_USER_NAME", "hadoop");
		Configuration conf = new Configuration();
		conf.set("fs.defaultFS", "hdfs://mikeal/");
		Job job = Job.getInstance(conf);
		job.setJarByClass(CleanData.class);
		job.setMapperClass(CleanDataMapper.class);
		job.setReducerClass(CleanDataReducer.class);
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(WebLogBean.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(NullWritable.class);
		Path in = new Path("/test/project1");
		Path out = new Path("/test/project1_out1");
		FileInputFormat.setInputPaths(job, in);
		FileSystem fs = FileSystem.get(conf);
		if (fs.exists(out)) {
			fs.delete(out, true);
		}
		FileOutputFormat.setOutputPath(job, out);
		job.waitForCompletion(true);
	}

}
